<?php
/**
 * Created by PhpStorm.
 * User: cnpscy
 * Date: 2020/7/7
 * Time: 22:57
 * Note: Admins.php
 */

namespace App\HttpController\Admin;

use App\Base\AdminController;
use App\Model\Log\AdminLoginLog;
use App\Model\Rabc\Admin;

class Logins extends AdminController
{
    protected function validate(Validate $validate)
    {
        return $validate->validate($this->request()->getRequestParam());
    }

    protected function getValidateRule(?string $action): ?Validate
    {

        // TODO: Implement getValidateRule() method.
        switch ($action) {
            case 'login':
                $valitor = new Validate();
                $valitor->addColumn('u_account')->required();
                $valitor->addColumn('u_password')->required();
                return $valitor;
                break;
        }
        return null;
    }

    public function login()
    {
        $params      = $this->request()->getRequestParam('admin_name', 'password');
        $admin_model = Admin::getInstance();
        $admin       = $admin_model->getInfoByWhere(['admin_name' => $params['admin_name']], 'admin_id, admin_name, password, is_check');
        if (!$admin) {
            return $this->errorJson('管理员不存在！');
        }
        if (!hash_verify($params['password'], $admin->password)) {
            return $this->errorJson('管理员与密码不匹配！');
        }
        switch ($admin->is_check) {
            case 0:
                return $this->errorJson('您的账户尚未启用！');
                break;
            case 2:
                return $this->errorJson('您的账户已被禁用，请联系管理员！');
                break;
        }

        // 登录用户的Token
        $token = $admin->getTokenByJwt($admin);

        //RedisPool::invoke(function (RedisObject $redis)use ($token,$user){
        //    $redis->set('admin_token_'.$token,json_encode($user), 36000);
        //});

        /**
         * 登录日志
         */
        // $this->request()->getHeader('user-agent')[0] 浏览器信息
        AdminLoginLog::createLog($params, $admin, 1, '登录成功', $this->request()->getMethod());

        return $this->successJson([
            'token' => $token,
            'admin' => $admin,
        ], 1, '登录成功');
    }
}